package fr.lelouet.tools.sequentialIterators;

import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.lelouet.tools.SequentialIterator;

/**
 * wait for {@link #tick()} before returning from
 * {@link #startNewLoop(Collection)}<br />
 * The {@link #startNewLoop(Collection)} will exit when a call to
 * {@link #tick()} has been done after last {@link #startNewLoop(Collection)}
 * terminated
 */
public class ClockDependant<T> implements SequentialIterator<T> {

	private static final Logger logger = LoggerFactory
			.getLogger(ClockDependant.class);

	protected Iterator<T> internalIt;

	protected boolean blockedOnNextLoop = true;

	@Override
	public boolean hasNext() {
		return internalIt.hasNext();
	}

	@Override
	public T next() {
		return internalIt.next();
	}

	@Override
	public void remove() {
		internalIt.remove();
	}

	@Override
	public void configure(Properties prop) {
	}

	@Override
	public void startNewLoop(Collection<T> requests) {
		logger.debug("starting new loop, waiting for tickle");
		while (blockedOnNextLoop) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				logger.info(e.toString() + " @ " + e.getStackTrace()[0]);
			}
		}
		blockedOnNextLoop = true;
		logger.debug("got the tickle");
		internalIt = requests.iterator();
	}

	/**
	 * makes any waiting call to {@link #startNewLoop(Collection)} to be awaken.
	 * If not such a call is being done, allow first next call to terminate.
	 */
	public void tick() {
		blockedOnNextLoop = false;
	}

}
